package com.boot.crm.plat.util;

import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * @Author: ys
 * @Date:Create in 2018/7/4 14:27
 * @Description:
 */
public class FileUtil {

    @Value("${file.formal.path}")
    private String fileFormalPath;//文件存放在本地的位置,举例:/home/administrator/crm_boot/
    private static final File DEFAULT_PARENT = new File(".");//文件夹默认的父文件夹
    private static final String APPLICATION_PROPERTIES = "/application.properties";
    private static final String FILE_FORMAL_PATH = "file.formal.path";  //配置文件application.properties中，路径的Key

    /**
     * 将一个文件或者文件夹(源文件)  复制到一个  文件或者文件夹中(目标文件)
     */
    public static void copyFile(File originFile,File toFile){
        if (null!=originFile && null!=toFile){
            if (toFile.isDirectory()){
                if (originFile.isDirectory()){
                    copyDirectory(originFile,toFile);
                }else if (originFile.isFile()){
                    copySimpleFile(originFile,new File(toFile,originFile.getName()));
                }
            }else if (toFile.isFile()){
                if (originFile.isDirectory()){
                    throw new IllegalStateException("文件夹不能复制进文件中");
                }
                copySimpleFile(originFile,toFile);
            }
//            else {
//                ensureParentFileWritable(toFile);
//                if (originFile.isDirectory()){
//                    toFile.mkdirs();
//                    copyDirectory(originFile,toFile);
//                }else if (originFile.isFile()){
//                    copySimpleFile(originFile,toFile);
//                }
//            }
        }
    }
    public static void copyDirectory(File originDirectory , File toDirectory){
        if (null != originDirectory && originDirectory.canRead()){
            if (!toDirectory.exists()){
                toDirectory.mkdirs();
            }
            String[] files = originDirectory.list();//字符串类型的文件名
            for (String file:files){
                File originDirFile = new File(originDirectory , file);//源文件夹下的  可能是文件也可能是文件夹
                if (originDirFile.canRead()){
                    if (originDirFile.isDirectory()){
                        copyDirectory(originDirFile,new File(toDirectory,file));//如果待复制(源)文件是文件夹，则采用递归进行复制
                    }else if (originDirFile.isFile()){
//                        copyFile(originDirFile,new File(toDirectory,file)); //两个单纯文件的复制
                        copySimpleFile(originDirFile,new File(toDirectory,file)); //两个单纯文件的复制
                    }
                }
            }
        }
    }

    /**
     * 判断一个文件夹是否可写(是否可以在该文件夹内新建文件或文件夹)
     * @param dir 文件夹
     * @return 该文件夹是否可写
     */
    public static boolean canWriteDir(File dir){
        return dir != null && dir.canWrite() && dir.isDirectory();
    }
    /**
     * 判断一个文件是否可写(是否可以在该文件内新建文件或文件夹)
     * @param file 文件夹
     * @return 该文件夹是否可写
     */
    public static boolean canWriteFile(File file){
        return file != null && file.canWrite() && file.isFile();
    }

    /**
     * 文件的复制(不涉及文件夹)
     * @param originFile 源文件
     * @param toFile 复制的目标文件
     */
    public static void copySimpleFile(File originFile,File toFile){
        InputStream is;
        OutputStream os;
        try {
            is = new FileInputStream(originFile);
            os = new FileOutputStream(toFile);
            byte[] buf = new byte[1024 * 1024];
            int bytesRead=0;
            if ((bytesRead=is.read(buf))!=-1){
                os.write(buf,0,bytesRead);
            }
            is.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void createFile(String fileName,String fileContent) throws IOException {
        fileName = getPropertiesFilePath() +fileName+".txt";
        File file = new File(fileName);
        if (!file.exists()){
            try {
                boolean newFile = file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        writeToFileContent(fileName,fileContent);
    }
    /**
     * 向文件中写入内(目前是只能写入.txt类型文件)
     * @param filePath 源文件路径
     * @param newStrContent 写入源文件的内容
     * @return 是否正确写入
     * @throws IOException 异常
     */
    public static boolean writeToFileContent(String filePath,String newStrContent) throws IOException {
        String temp = "";
        InputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        OutputStream fos = null;
        PrintWriter pw = null;
        boolean bool = false;
        try {
            File file = new File(filePath);//文件路径(包括文件名称)
            //将文件读入输入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis,"utf-8");//处理字符流，是字符流通向字节流的桥梁
            br = new BufferedReader(isr);//提供通用的缓存方式读取，readline读取一个文本行
            StringBuilder stringBuilder = new StringBuilder();
            while ((temp = br.readLine())!=null){
                stringBuilder.append(temp);
                //行与行之间的分隔符相当于“\n”
                stringBuilder.append(System.getProperty("line.separator"));
            }
            stringBuilder.append(newStrContent);
            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(stringBuilder.toString().toCharArray());
            pw.flush();
            bool = true;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null != pw){
                pw.close();
            }
            if (null != fos){
                fos.close();
            }
            if(null != br){
                br.close();
            }
            if(null != isr){
                isr.close();
            }
            if (null != fis){
                fis.close();
            }
        }
        return bool;
    }

    public static void main(String[] args) throws IOException {
//        boolean b = writeToFileContent("C:\\Users\\wanda\\Desktop\\test6.docx", "sssssssssssssssssss");
//        File file = new File("C:\\Users\\wanda\\Desktop\\居民端\\test");
//        File file1 = new File("C:\\Users\\wanda\\Desktop\\123");
//        copyFile(file,file1);
//        File file = new File("d:\\test\\tests.txt");
//        boolean exists = file.exists();
//        String configPath = FileUtil.getPropertiesFilePath();
//        System.out.println("properties路径："+configPath);
//        createFile("stream","这是我的梦想");
          getDirectoryAllFileName(new File("/home"),0);
//        getFile(new File("/home"),0);
//        System.out.println(directoryAllFileName);
//        String [] strings = new String[]{"12","3","4","5"};
//        List<String> list = Arrays.asList(strings);
//        list.remove(0);
    }

    /**
     * 1.验证传递进来的file是否有效，2.验证并创建file的父文件路径
     * @param file 传递进来的 toFile(最终目标文件)
     */
    public static void ensureParentFileWritable(File file){
        if(null == file){
            throw new IllegalStateException("传递进来的文件无效");
        }
        File parentFile = file.getParentFile();
        if (null == parentFile){
            parentFile = DEFAULT_PARENT;
        }
        if (!parentFile.canWrite()){
            parentFile.mkdirs();
        }
    }


    /**
     * 获取配置文件中的设定的文件(夹)路径
     * @return 文件夹路径
     * @throws IOException 异常
     */
    public static String getPropertiesFilePath() throws FileNotFoundException {
        InputStream is = getPropertiesInputStream();
        InputStream is2 = getPropertiesInputStreamType2();
        Properties properties = new Properties();
        try {
            properties.load(is);
            if (null != is){
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String fileFormalPath = properties.getProperty(FILE_FORMAL_PATH);
        if (null != fileFormalPath){
            File file = new File(fileFormalPath);
            if (!file.exists()){
                file.mkdirs();
            }
            return fileFormalPath;  //配置文件中，设定的路径
        }
        return null;
    }

    /**
     * 获取配置文件application.properties的输入流
     * 注意：class.getResourceAsStream 直接获取文件输入流
     * @return 文件输入流
     */
    public static InputStream getPropertiesInputStream(){
        return FileUtil.class.getResourceAsStream(APPLICATION_PROPERTIES);
    }

    /**
     * 获取配置文件application.properties的输入流
     * 注意：如果1.z中的参数带有'/'则从ClassPath根目录下获取文件，如果不带'/'则是从当前类所在包下查找
     * @return 文件输入流
     * @throws FileNotFoundException 异常
     */
    public static InputStream getPropertiesInputStreamType2() throws FileNotFoundException {
        URL resource = FileUtil.class.getResource(APPLICATION_PROPERTIES);  //1.
        File file = new File(resource.getFile());
        return new FileInputStream(file);
    }
    //获取文件夹内所有文件夹及文件的名称
    public static void getDirectoryAllFileName(File file,int deep){
            File[] array = file.listFiles();
            for(File file1:array){
                if (file1.isFile()){
                    for (int i=0;i<deep;i++){
                        System.out.print(" ");
                    }
                    System.out.println(file1.getName());
                }
                else if (file1.isDirectory()){
                    for (int i=0;i<deep;i++){
                        System.out.print(" ");
                    }
                    System.out.println(file1.getName());
                    getDirectoryAllFileName(file1,++deep);
                }
            }
        }
    private static void getFile(File file,int deep){
//        File file = new File(path);
        File[] array = file.listFiles();
        for(File file1:array){
            if(file1.isFile()){
                for (int j = 0; j < deep; j++)//输出前置空格
                    System.out.print(" ");
                System.out.println( file1.getName());
            }
            else if(file1.isDirectory()){
                for (int j = 0; j < deep; j++)//输出前置空格
                    System.out.print(" ");
                System.out.println( file1.getName());
//                getFile(file1.getPath(),deep+1);
                getFile(file1,deep+1);
            }
        }
    }
//
}
